/* Copyright © 2010 LPRM
Universidade Federal do Espírito Santo - RNP-GT CWTools

This file is part of JoinUs!.

JoinUs! is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

JoinUs! is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with JoinUs!. If not, see <http://www.gnu.org/licenses/>. */
package br.ufes.cwtools.joinus.home;

import java.io.StringReader;
import java.util.Vector;

import org.xml.sax.InputSource;

import br.ufes.cwtools.joinus.home.communities.Commu;
import br.ufes.cwtools.joinus.home.communities.CommuShow;
import br.ufes.cwtools.joinus.home.communities.ShowCommSearch;
import br.ufes.cwtools.joinus.home.core.NewInvitations;
import br.ufes.cwtools.joinus.profile_manager.profile.General;
import br.ufes.cwtools.joinus.util.DBHelper;
import br.ufes.cwtools.joinus.util.ServerCom;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import br.ufes.cwtools.joinus.R;
import android.os.SystemClock;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/*
 * This class is responsable for creating an empty listView containner 
 * for 3 screens: Campaings, Invitations and Comunities.
 */

public class ListViewFactory {
	SQLiteDatabase myBase;
	LayoutInflater viewInflate;
	Activity a;
	ListView v;
	int id;
	MyListAdapter myAdapter;
	long[] keys;
	FileManager fm;

	ListViewFactory(Activity a, SQLiteDatabase myBase, int id) {
		this.myBase = myBase;
		this.a = a;
		this.id = id;
		((Home2) a).setPreviousScreen(Home2.HOME);

		switch (id) {
		case 0:
			buildInvitations(a);
			a.setTitle("JoinUs - Invitations");
			this.v = (ListView) a.findViewById(R.id.list_view_factory_list_view);
			loadInvitationData();
			setUpInviButs();
			v.setOnItemClickListener(new MyOnClick());
			break;
		case 2:
			a.setTitle("JoinUs - Communities");
			buildComm(a);
			this.v = (ListView) a.findViewById(R.id.list_view_factory_list_view);
			v.setOnItemClickListener(new MyOnClick());
			downloadCommu();
			setUpCommuButs();
			loadCommuData();
			setupListListener();
			break;
		case 3:
			a.setTitle("JoinUs - Contacts");
			buildCon(a);
			this.v = (ListView) a.findViewById(R.id.list_view_factory_list_view);
			v.setOnItemClickListener(new MyOnClick());
			downloadCon();
			setUpConButs();
			break;
		case 4:
			a.setTitle("JoinUs - Messages");
			buildMsgs(a);
			this.v = (ListView) a.findViewById(R.id.list_view_factory_list_view);
			v.setOnItemClickListener(new MyOnClick());
			downloadMsgs();
			setupMenButs();
			break;
		case 5:
			Intent i = new Intent(this.a, FileManager.class);
			this.a.startActivity(i);
			break;
		}
	}

	public void displayFile(String[][] f) {
		/*
		 * RelativeLayout[] rl = new RelativeLayout[f.length];
		 * 
		 * for(int i = 0; i < f.length; i++) { RelativeLayout r =
		 * (RelativeLayout) viewInflate.inflate(R.layout.line_template_fm, null,
		 * null); ((TextView) r.getChildAt(0)).setDrawable(toAdd[i][0]); if (id ==
		 * 0) { ((TextView) r.getChildAt(2)).setText("Sender: " + toAdd[i][1]); }
		 * else if(id == 3){ ((TextView) r.getChildAt(2)).setText("User id: " +
		 * toAdd[i][1]); }else{ ((TextView) r.getChildAt(2)).setText("Creator: " +
		 * toAdd[i][1]); } rl[i] = r; } v.setAdapter(new MyListAdapter(rl));
		 */
	}

	@SuppressWarnings("unused")
	private void getAllFiles(SQLiteDatabase db) {
		Cursor c = db.query("fileInfo", null, "*", null, null, null, null);
		String[][] f = new String[c.getCount()][4];

		for (int i = 0; i < c.getCount(); ++i) {
			c.moveToPosition(i);
			f[i][0] = new String(c.getString(2));
			f[i][1] = new String(c.getString(3));
			f[i][2] = new String(c.getString(4));
			f[i][3] = new String(c.getString(5));
		}
		
		c.close();

		displayFile(f);
	}

	@SuppressWarnings("unused")
	private void buildFileManager(Activity a) {
		a.setContentView(R.layout.listviewfactory);
		RelativeLayout relative = (RelativeLayout) a.findViewById(R.id.list_view_factory_inner_layout);
		viewInflate = LayoutInflater.from(a);
		viewInflate.inflate(R.layout.filemanager, relative);
	}

	private void setupStatusSpinner() {
		String s[] = { "Downloading", "Paused", "Ready to open", "All" };

		Spinner spinner = (Spinner) a.findViewById(R.id.statusspinner);
		ArrayAdapter<CharSequence> spinnerOptions = new ArrayAdapter<CharSequence>(
				a, android.R.layout.simple_spinner_dropdown_item);

		for (String i : s)
			spinnerOptions.add(i); //spinnerOptions.addObject(i);

		spinnerOptions.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(spinnerOptions);
	}

	private void setupTypeSpinner() {
		String s[] = { "Image", "Sound", "Document", "All" };

		Spinner spinner = (Spinner) a.findViewById(R.id.typespinner);
		ArrayAdapter<CharSequence> spinnerOptions =
			new ArrayAdapter<CharSequence>(a, android.R.layout.simple_spinner_dropdown_item);

		for (String i : s)
			spinnerOptions.add(i);

		spinnerOptions.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(spinnerOptions);
	}

	@SuppressWarnings("unused")
	private void setupFileManagerButt() {
		Button b1 = (Button) a.findViewById(R.id.fm_list_view_factory_filter);

		b1.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				a.setContentView(R.layout.filter);
				((Home2) a).setPreviousScreen(Home2.FMANAGER);
				setupStatusSpinner();
				setupTypeSpinner();
			}
		});
	}

	private void downloadMsgs() {
		DBHelper toRecord = new DBHelper();
		toRecord.onCreate(myBase);
		Cursor query = myBase.query("messages", null, "user='"
				+ ((Home2) a).getUsername() + "'", null, null, null, null);
		query.moveToPosition(0);
		String toAdd[][] = new String[query.getCount()][];
		keys = new long[query.getCount()];
		for (int i = 0; i < query.getCount(); i++) {
			toAdd[i] = new String[2];
			query.moveToPosition(i);
			toAdd[i][0] = query.getString(1);
			toAdd[i][1] = ServerCom.getUserName(query.getString(2))+" ("+query.getString(2)+")";
			keys[i] = query.getInt(query.getColumnIndex("id"));
		}
		query.close();
		add(toAdd);
	}

	private void setupListListener() {
		v.setOnItemClickListener(new OnItemClickListener() {
			long lastClickTime = 0;
			long lastId = -1;

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				if (SystemClock.elapsedRealtime() - lastClickTime < 500 && lastId == arg3) {
					new CommuShow(keys[(int) arg3], a, myBase, ((Home2)a).getUsername()); // Bad Ass Lennin ROX!
				}
				lastClickTime = SystemClock.elapsedRealtime();
				lastId = arg3;
			}
		});
	}

	private void buildInvitations(Activity a) {
		a.setContentView(R.layout.listviewfactory);
		RelativeLayout relative = (RelativeLayout) a.findViewById(R.id.list_view_factory_inner_layout);
		viewInflate = LayoutInflater.from(a);
		viewInflate.inflate(R.layout.invitations, relative);
	}

//	private void buildCamp(Activity a) {
//		a.setContentView(R.layout.listviewfactory);
//		RelativeLayout relative = (RelativeLayout) a.findViewById(R.id.list_view_factory_inner_layout);
//		viewInflate = LayoutInflater.from(a);
//		viewInflate.inflate(R.layout.campaigns, relative);
//	}

	private void buildMsgs(Activity a) {
		a.setContentView(R.layout.listviewfactory);
		RelativeLayout relative = (RelativeLayout) a.findViewById(R.id.list_view_factory_inner_layout);
		viewInflate = LayoutInflater.from(a); //
		viewInflate.inflate(R.layout.msg, relative);//, null);
	}

	private void buildComm(Activity a) {
		a.setContentView(R.layout.listviewfactory);
		RelativeLayout relative = (RelativeLayout) a.findViewById(R.id.list_view_factory_inner_layout);
		viewInflate = LayoutInflater.from(a); //
		viewInflate.inflate(R.layout.community, relative); //, null);
	}

	private void buildCon(Activity a) {
		a.setContentView(R.layout.listviewfactory);
		RelativeLayout relative = (RelativeLayout) a.findViewById(R.id.list_view_factory_inner_layout);
		viewInflate = LayoutInflater.from(a);
		viewInflate.inflate(R.layout.contact2, relative);
	}

	public void add(String[][] toAdd) {
		RelativeLayout[] rl = new RelativeLayout[toAdd.length];
		for (int i = 0; i < toAdd.length; i++) {
			RelativeLayout r = (RelativeLayout) viewInflate.inflate(R.layout.line_template, null);
			((TextView) r.getChildAt(1)).setText(toAdd[i][0]);
			if (id == 0) {
				((TextView) r.getChildAt(2)).setText("Sender: " + toAdd[i][1]);
			} else if (id == 3) {
				((TextView) r.getChildAt(2)).setText("User id: " + toAdd[i][1]);
			} else {
				((TextView) r.getChildAt(2)).setText("Creator: " + toAdd[i][1]);
			}
			rl[i] = r;
		}
		v.setAdapter(new MyListAdapter(rl));
	}

	private void downloadCommu() {
		String xml = ServerCom.getCommu();
		InputSource is = new InputSource();
		is.setCharacterStream(new StringReader(xml));
		Commu factory = new Commu();
		Vector<Commu> commu = factory.fromXml(is);
		for (Commu c : commu) {
			c.toDataBase(myBase, ((Home2) a).getUsername());
		}
		loadCommuData();
	}

	private void downloadCon() {
		if (!((Home2) a).contCheck) {
			Vector<Contacts> contList;
			String result = ServerCom.getContacts();
			contList = Contacts.fromXml(result);
			String[][] queryResult = new String[contList.size()][];
			int i = 0;
			keys = new long[contList.size()];
			for (Contacts c : contList) {
				String xml = "<resources>" + ServerCom.getContactInfoLite(Long.toString(c.id)) + "</resources>";
				General profile = new General();
				InputSource is = new InputSource();
				is.setCharacterStream(new StringReader(xml));
				profile.fromXML(is);
				queryResult[i] = new String[2];
				queryResult[i][0] = "Name: " + profile.firstName + " " + profile.lastName;
				queryResult[i][1] = "" + c.id;
				keys[i] = c.id;
				try {
					myBase.execSQL("INSERT INTO contacts VALUES ("+c.id+",'"+queryResult[i][0]+"','"+((Home2)a).getUsername()+"');");
				} catch (SQLException e) {
					Log.d("SQLERROR","id repetida"+c.id);
				}
				i++;
			}
			add(queryResult);
			((Home2) a).contCheck = true;
		} else {
			Cursor query = myBase.query("contacts", null, "user='"
					+ ((Home2) a).getUsername() + "'", null, null, null, null);
			String[][] array = new String[query.getCount()][];
			keys = new long[query.getCount()];
			for (int i = 0; i < query.getCount(); i++) {
				query.moveToPosition(i);
				array[i] = new String[] { query.getString(1),query.getString(0) };
				keys[i] = query.getLong(0);
			}
			
			query.close();
			
			add(array);
		}
	}

	private void loadCommuData() {
		Cursor query = myBase.query("communities", null, "user='"
				+ ((Home2) a).getUsername() + "'", null, null, null, null);
		String[][] array = new String[query.getCount()][];
		keys = new long[query.getCount()];
		for (int i = 0; i < query.getCount(); i++) {
			query.moveToPosition(i);
			array[i] = new String[] { query.getString(1), ServerCom.getUserName(query.getString(2))+" ("+query.getString(2)+")" };
			keys[i] = query.getLong(0);
		}
		
		query.close();
		
		add(array);
	}

	private void createCommu() {
		String name, desc;
		name = ((EditText) a.findViewById(R.id.create_commu_edit_name)).getText().toString();
		desc = ((EditText) a.findViewById(R.id.create_commu_edit_desc)).getText().toString();

		String userfix = ((Home2) a).getUsername().replaceAll("\'|\"", "''"); 
		String desc_fix=desc.replaceAll("\'|\"", "''"); 
		String name_fix= name.replaceAll("\'|\"", "''"); 
		ServerCom.createCommu(name_fix, desc_fix, userfix, 1, 1);
	}

	private void setupMenButs() {

		ImageButton b = (ImageButton) a.findViewById(R.id.list_view_factory_comm_unjoin);
		b.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				boolean changed = false;
				for (int i = 0; i < v.getCount(); i++) {
					RelativeLayout r = (RelativeLayout) v.getAdapter().getView(i, null, null);
					CheckBox cb = (CheckBox) r.getChildAt(0);
					if (cb.isChecked()) {
						changed = true;
						myBase.execSQL("DELETE FROM messages" +
								" WHERE id=" + keys[i] + 
								" AND user='" + ((Home2) a).getUsername() + "';");
					}
				}
				if (changed) {
					downloadMsgs();
				}
			}
		});

	}

	private void setUpConButs() {
		ImageButton ib;
		ib = (ImageButton) a.findViewById(R.id.list_view_factory_comm_search);
		ib.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				final Dialog search;
				search = new Dialog(v.getContext());
				search.setContentView(R.layout.search);
				search.setTitle("Search");

				ImageButton b = (ImageButton) search.findViewById(R.id.SearchButton);
				b.setOnClickListener(new OnClickListener() {
					public void onClick(View arg0) {
						Vector<Contacts> contList;
						String result = ServerCom.searchContacts(((EditText) search.findViewById(R.id.SearchField)).getText().toString());
						if(result!=null){
							contList = Contacts.fromXml(result);
							String[][] queryResult = new String[contList.size()][];
							int i = 0;
							for (Contacts c : contList) {
								String xml = ServerCom.getContactInfoLite(c.id + "");
								General profile = new General();
								InputSource is = new InputSource();
								is.setCharacterStream(new StringReader(xml));
								profile.fromXML(is);
								queryResult[i] = new String[2];
								queryResult[i][0] = "Name: " + profile.firstName + " " + profile.lastName;
								queryResult[i][1] = "" + c.id;

								i++;
							}
							new ContactQueryShow(queryResult, a, myBase);
							search.dismiss();
						}else{
							Toast.makeText(a, "Invalid Regular Expression!", Toast.LENGTH_LONG).show();
						}
					}
				});
				search.show();
			}
		});

		ib = (ImageButton) a.findViewById(R.id.list_view_factory_comm_unjoin);
		ib.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				boolean changed = false;
				for (int i = 0; i < v.getCount(); i++) {
					RelativeLayout r = (RelativeLayout) v.getAdapter().getView(
							i, null, null);
					CheckBox cb = (CheckBox) r.getChildAt(0);
					if (cb.isChecked()) {
						changed = true;
						ServerCom.deleteContact(keys[i] + "");
						myBase.execSQL("DELETE from contacts where id="
								+ keys[i] + " and user='"
								+ ((Home2) a).getUsername() + "';");
					}
				}
				if (changed) {
					downloadCon();
				}
			}
		});

		ImageButton b = (ImageButton) a.findViewById(R.id.list_view_factory_comm_create);

		b.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				((Home2) a).setPreviousScreen(Home2.CONT);
				a.setContentView(R.layout.send_msg);
				Button b = (Button) a.findViewById(R.id.msg_send);

				final long toSendList[] = new long[v.getCount() + 1];
				int c = 0;
				for (int i = 0; i < v.getCount(); i++) {
					RelativeLayout r = (RelativeLayout) v.getAdapter().getView(i, null, null);
					CheckBox cb = (CheckBox) r.getChildAt(0);
					if (cb.isChecked()) {
						toSendList[c] = keys[i];
						c++;
					}
				}
				toSendList[c] = -1;

				b.setOnClickListener(new OnClickListener() {
					public void onClick(View arg0) {
						int c = 0;
						if(((EditText) a.findViewById(R.id.msg_to_send)).getText().toString().compareTo("")==0){
							return;
						}
						while (toSendList[c] != -1) {
							String toSend = ((EditText) a.findViewById(R.id.msg_to_send)).getText().toString();

							toSend = toSend.replaceAll("\'|\"", "''");
							toSend = toSend.replaceAll("\n", " ");

							ServerCom.sendMsg(toSendList[c] + "", toSend);
							c++;
						}
						((EditText)a.findViewById(R.id.msg_to_send)).setText("");
					}
				});
			}
		});

	}

	private void setUpCommuButs() {
		ImageButton b = (ImageButton) a.findViewById(R.id.list_view_factory_comm_create);
		b.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				a.setContentView(R.layout.create_commu);
				((Home2) a).setPreviousScreen(Home2.COMMU);
				Button b = (Button) a.findViewById(R.id.create_commu_edit_but);
				b.setOnClickListener(new OnClickListener() {
					public void onClick(View arg0) {
						createCommu();
						a.setTitle("Join Us! - Communities");
						buildComm(a);
						ListViewFactory.this.v = (ListView) a.findViewById(R.id.list_view_factory_list_view);
						v.setOnItemClickListener(new MyOnClick());
						downloadCommu();
						setUpCommuButs();
						loadCommuData();
						setupListListener();
					}
				});
			}
		});

		ImageButton ib = (ImageButton) a.findViewById(R.id.list_view_factory_comm_search);
		ib.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				final Dialog search;
				search = new Dialog(v.getContext());
				search.setContentView(R.layout.search);
				search.setTitle("Search");

				ImageButton b = (ImageButton) search.findViewById(R.id.SearchButton);
				b.setOnClickListener(new OnClickListener() {
					public void onClick(View arg0) {
						new ShowCommSearch(((EditText) search.findViewById(R.id.SearchField)).getText().toString(), a);
						search.dismiss();
					}
				});
				search.show();
			}
		});

		ib = (ImageButton) a.findViewById(R.id.list_view_factory_comm_unjoin);
		ib.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				for (int i = 0; i < v.getCount(); i++) {
					RelativeLayout r = (RelativeLayout) v.getAdapter().getView(i, null, null);
					CheckBox cb = (CheckBox) r.getChildAt(0);
					if (cb.isChecked()) {
						ServerCom.quitCommu(keys[i] + "", ServerCom.getMyId());
						myBase.execSQL("DELETE FROM communities WHERE id="
								+ keys[i] + " and user='"
								+ ((Home2) a).getUsername() + "';");
					}
				}
				loadCommuData();
			}
		});
	}

	// Obsoleto com CampaignListView
//	private void setUpClick() {
//		Log.d("ListViewFactory", "setUpClick() called.");
//		ListView lv = this.v;
//		//ListView l = (ListView) a.findViewById(R.id.list_view_factory_list_view);
//		
//		lv.setOnItemClickListener(new OnItemClickListener() {
//			@Override
//			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//				Log.d("ListViewFactory", "onItemClick() called for campaigns list.");
//				Intent intent = new Intent(a, CampDetails.class);
//				Bundle extra = new Bundle();
//				extra.putString("id", keys[position] + "");
//				extra.putString("user", ((Home2) a).getUsername());
//
//				intent.putExtras(extra);
//				a.startActivity(intent);
//			}
//		});
//	}

	private void setUpEraseBut(Activity layout) {
		ImageButton b = (ImageButton) layout.findViewById(R.id.list_view_factory_button_reject);
		b.setOnClickListener(new OnClickListener() {
			public void onClick(View parent) {
				boolean changed = false;
				for (int i = 0; i < v.getAdapter().getCount(); i++) {
					RelativeLayout r = (RelativeLayout) v.getAdapter().getView(
							i, null, null);
					CheckBox cb = (CheckBox) r.getChildAt(0);
					if (cb.isChecked()) {
						changed = true;
						myBase.execSQL("DELETE FROM activeInvitations WHERE id="
								+ keys[i]+ " and user='"+ ((Home2) a).getUsername() + "';");
					}
				}
				if (changed) {
					loadInvitationData();
				}
			}
		});
	}

	// Obsoleto com CampaignListView
//	private void setUpCampButs() {
//		ImageButton b = (ImageButton) a.findViewById(R.id.list_view_factory_camp_create);
//		b.setOnClickListener(new OnClickListener() {
//			public void onClick(View arg0) {
//				((Home2) a).previousScreen = Home2.CAMP;
//				a.setContentView(R.layout.camp_creator);
//				new CampCreate().setUp(myBase, a);
//			}
//		});
//
//		ImageButton c = (ImageButton) a.findViewById(R.id.list_view_factory_camp_unjoin);
//		c.setOnClickListener(new OnClickListener() {
//			public void onClick(View arg0) {
//				boolean changed = false;
//				for (int i = 0; i < v.getCount(); i++) {
//					RelativeLayout r = (RelativeLayout) v.getAdapter().getView(
//							i, null, null);
//					CheckBox cb = (CheckBox) r.getChildAt(0);
//					if (cb.isChecked()) {
//						myBase.execSQL("DELETE FROM activeCamp WHERE id="
//								+ keys[i] + ";");
//						changed = true;
//					}
//				}
//				if (changed) {
//					loadCampData();
//				}
//			}
//		});
//	}

	private void setUpInviButs() {
		setUpEraseBut(a);
		setUpEnter();
	}

	private void setUpEnter() {
		ImageButton b = (ImageButton) a.findViewById(R.id.list_view_factory_button_accept);
		b.setOnClickListener(new OnClickListener() {
			public void onClick(View parent) {
				boolean changed = false;
				Cursor query;
				for (int i = 0; i < v.getAdapter().getCount(); i++) {
					RelativeLayout r = (RelativeLayout) v.getAdapter().getView(i, null, null);
					CheckBox cb = (CheckBox) r.getChildAt(0);
					if (cb.isChecked()) {
						changed = true;
						query = myBase.query("activeInvitations", null,
								"id=" + keys[i] + " and user='" + ((Home2) a).getUsername() + "'",
								null, null, null, null);
						query.moveToPosition(0);

						myBase.execSQL("INSERT INTO activeCamp (campName, id, user, authorName, desc, expDate, status, public) VALUES ('"
								+ query.getString(query.getColumnIndex("campName"))
								+ "'," + keys[i] + ",'" + ((Home2) a).getUsername()
								+ "','" + query.getString(query.getColumnIndex("authorName"))
								+ "','" + query.getString(query.getColumnIndex("desc"))
								+ "','" + query.getString(query.getColumnIndex("expDate"))
								+ "','0','" + query.getString(query.getColumnIndex("public")) +"');");
						
						query.close();

						myBase.execSQL("DELETE FROM activeInvitations WHERE id="
								+ keys[i] + " and user='" + ((Home2) a).getUsername() + "';");
						String resp = ServerCom.joinCampaign(((Home2) a).getUsername(), ((Home2) a).getPassword(), keys[i]);
						Log.d("inviresp",resp);
					}
				}
				if (changed) {
					loadInvitationData();
				}
			}
		});
	}

	final class MyOnClick implements OnItemClickListener {
		Vector<Integer> Selected;
		public void onItemClick(AdapterView<?> list, View v, int positon, long id) { }
	}

	private void loadInvitationData() {
		Cursor query = myBase.query("localdata", null, null, null, null, null, null);
		if (query.getCount() != 1) {
			Log.d("DEBUG", "FIXME: DATA BASE INCONSISTENCY COUNT =" + query.getCount());
		}
		query.moveToPosition(0);
		int latitude = query.getInt(0);
		int longitude = query.getInt(1);
		query.close();

		String xml = ServerCom.getInvitations(((Home2) a).getUsername(),
				((Home2) a).getPassword(), latitude + "", longitude + "");
		InputSource is = new InputSource();
		is.setCharacterStream(new StringReader(xml));
		NewInvitations factory = new NewInvitations();
		// Lê o xml de convites a partir de um arquivo teste; pode remover.
		//is =  new InputSource(a.getResources().openRawResource(R.raw.test_invites));
		Vector<NewInvitations> invi = factory.fromXml(is);
		for (NewInvitations i : invi) {
			i.toDataBase(myBase, ((Home2) a).getUsername());
		}
		LoadInviSQLIntoList(myBase, a);
	}

	private void LoadInviSQLIntoList(SQLiteDatabase myBase, Activity a) {
		Cursor query = myBase.query("activeInvitations", null, "user='"
				+ ((Home2) a).getUsername() + "'", null, null, null, null);
		String[][] array = new String[query.getCount()][];
		keys = new long[query.getCount()];
		for (int i = 0; i < query.getCount(); i++) {
			query.moveToPosition(i);
			array[i] = new String[] { query.getString(1), query.getString(2) };
			keys[i] = query.getLong(0);
		}
		
		query.close();
		
		add(array);
	}

	final class MyListAdapter extends BaseAdapter {
		RelativeLayout[] item;

		public MyListAdapter(RelativeLayout[] v) {
			item = v;
		}

		public Object getItem(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			return item[position];
		}

		public long getItemId(int position) {
			return position;
		}

		public int getCount() {
			return item.length;
		}
	}
}
